<?php

/**
 * @Author:      lyt
 * @DateTime:  2017-03-25 15:18:05
 * @Description: 用于 洗车单的退款
 */
class ScsReturnWashOrderController extends BaseController
{
    
   /**
    * @Author:      lyt
    * @DateTime:  2017-03-25 15:25:25
    * @Description: 用于显示 洗车单的详情
    */
    public function returnWashOrderShow(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "return_order_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $return_order_id = Input::get('return_order_id');
            $ro=ReturnCarwashOrder::find($return_order_id);
            if(is_null($ro) || $ro->status==2){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }

            $orders=CarWashOrder::where('order_id',$ro->order_id)
                ->select('car_wash_order.order_id','car_wash_order.pay_time','car_wash_order.phone','car_wash_order.car_no','car_wash_order.producd_id')
                ->first();
            $product=Config::get('config.wash_product');
            $orders->product_name=$product[$orders->producd_id];
            $opr=CarWashOrderPayRecord::where('order_id',$ro->order_id)->where('status',1)->select('id','pay_type','amount')->get();
            
            $return_money = [];
            $ror =[];
            // 如果状态是未执行，不返回退款结果
            if ($ro->status != 0) {
                $ror=ReturnWashOrderRecord::where('return_washorder_id',$return_order_id)->get();
                $return_record = AcountUserRechargeSpendRe::returnOrderSpendMoney($return_order_id);
                if (!empty($return_record)) {
                    foreach ($return_record as $value) {
                            $array = AcountUserRecharge::RechargeInfo($value->aurr_id); //根据充值记录，查找对应的门店名称和账户标虚
                            
                            $key = $array['shop_id'].'_'.$array['acount_type'];
                            if(isset($return_money[$key])){
                                $return_money[$key]['amount'] += $value->amount;
                            } else {
                                $return_money[$key] = $array;
                                $return_money[$key]['amount'] = $value->amount;
                            }
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order"=>$orders,"return_order"=>$ro,"order_pay_record"=>$opr,'return_order_record'=>$ror,"return_money"=>  array_values($return_money)));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "returnWashOrderShow", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
  
    /**
     * @Author:      lyt
     * @DateTime:  2017-03-27 09:42:22
     * @Description: 创建退货单
     */
    public function createReturnOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "order_id"=>'required',
                "reason"=>'required',
                "note"=>'max:140',
                "type"=>'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=CarWashOrder::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if(!in_array($orders->status,array(1417))){
                $response = Lang::get("scs_error.order_return_error_40053");
                break;
            }
            $returnOrder=ReturnCarwashOrder::whereIn('status',array(0,1))->where('order_id',Input::get('order_id'))->get();
            if(sizeof($returnOrder)>0){
                $response = Lang::get("scs_error.order_return_error_40043");
                break;
            }           
            $ro = new ReturnCarwashOrder();
            $return_order_id = Common::createOrderId();
            $ro->id = $return_order_id;
            $ro->order_id = Input::get('order_id');
            $ro->reason =Input::get('reason');
            $ro->note = Input::get('note')?Input::get('note'):'';
            $ro->amount = $orders->pay_amount;
            $ro->created_by = $sc_user->id;
            $ro->created_name = $sc_user->real_name;
            $ro->status = 0;
            $ro->save();
            
            $ror=CarWashOrderPayRecord::where("order_id",$orders->order_id)->first();//找到原洗车单的支付记录
            $rwo=new ReturnWashOrderRecord;
            $rwo->return_washorder_id=$return_order_id;
            $rwo->pay_type=$ror->pay_type;
            $rwo->amount=$ror->amount;
            $rwo->type=Input::get('type');
            $rwo->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("return_order_id"=>$return_order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "createReturnOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author: lyt
     * @DateTime:  2017-03-27 11:40:49
     * @Description: 取消洗车退货单
     */
    public function cancelReturnOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "return_order_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $or=ReturnCarwashOrder::find(Input::get('return_order_id'));
            // if(is_null($or) || $or->status==2){
            if(is_null($or) || $or->status==2||$or->status==1){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }            
            $or->status=2;
            $or->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "cancelReturnOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    } 
    
    
    
   
    /**
     * @Author:      lyt
     * @DateTime:  2017-03-27 13:47:35
     * @Description: 洗车退款单
     */
    public function accredit(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "return_order_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $ro=ReturnCarwashOrder::find(Input::get('return_order_id'));
            if(is_null($ro) || $ro->status==2){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }
            
            $orders=CarWashOrder::find($ro->order_id);
            $date=date('Y-m-d',time());
            $paytime=explode(' ',$orders->pay_time);
            if($paytime[0]==$date){
                $accredit_type=array(
                    array("type"=>0),
                    array("type"=>1)
                    );
                $me=SCUser::where('status',1)->where('shop_id',$sc_user->shop_id)->where('title',1)->select('id','real_name')->get();
                $result=array('accredit_type'=>$accredit_type,'shop_manager'=>$me);
                
            }else{
                 $accredit_type=array(
                    array("type"=>1)
                    );
                 $temp_ca=CityAuthorization::where("city_id",$sc_user->shop->city_id)->where("return",1)->where("status",1)->select("id","name")->get();
                 $result=array('accredit_type'=>$accredit_type,'approver'=>$temp_ca);
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "accredit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      lyt
     * @DateTime:  2017-03-27 16:04:30
     * @Description:  执行 退款单
     */
    public function implementReturnOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "return_order_id"=>'required',
                "type"=>'required',
                "code"=>'numeric',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            if(Input::get('type')==1){
                $phone="";
                $area="010";
                $id=Input::get('id');
                $ca=CityAuthorization::find($id);
                $phone=$ca->phone;
                $approver=0;
                $approver_name=$ca->name;
                //判断验证码是否存在
                $record = UserCheckCodeUpgrade::where('business_id',Input::get('return_order_id'))->where("business_type","return_washorder")->where("phone",$phone)->first();
                if(is_null($record)){ //没有记录
                    $response = Lang::get("error.user_login_checkcode_null_1012");
                    break;
                }
                //校验是否超过时限
                if( time() > Common::datetime2Num($record->out_time_at) ){
                    $response = Lang::get("error.user_login_checkcode_timeout_1013");
                    break;
                }
        
                //校验验证码是否匹配
                if($record->check_code != Input::get('code')){
                    $response = Lang::get("error.user_login_checkcode_error_1014");
                    break;
                }
            }else{
                $sc=SCUser::where('user_name',Input::get('username'))->where('password',strtoupper(md5(Input::get('password'))))->where('status',1)->first();
                if(is_null($sc)){
                    $response = Lang::get("scs_error.scs_user_not_exiet21009");
                    break;
                }
                if($sc->title!=1){
                    $response = Lang::get("scs_error.login_user_error_21016");
                    break;
                }
                $approver=$sc->id;
                $approver_name=$sc->real_name;
            }
            
            $ro=ReturnCarwashOrder::find(Input::get('return_order_id'));
            if(is_null($ro) || $ro->status!=0){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }
            $response=ReturnCarwashOrder::refund(Input::get('return_order_id'),$approver,$approver_name);
            // (Input::get('return_order_id'),$roi,$ro->order_id,$sc_user,$ro, $approver,$approver_name,$return_type);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "implementReturnOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
  /**
   * @Author:      lyt
   * @DateTime:  2017-03-27 14:24:35
   * @Description: 验证发送短信 
   */
    public function sendMessage(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "id"=>'required',
                "return_order_id"=>'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            $phone="";
            $area='';
            $return_order_id=Input::get('return_order_id');
            $id=Input::get('id');
            $ca=CityAuthorization::find($id);
            $phone=$ca->phone;
            $time_out_default = Config::get("user.time_out_default");

            
            //检查手机号是否下发验证码
            $record = UserCheckCodeUpgrade::where('business_id',Input::get("return_order_id"))->where("business_type","return_washorder")->where("phone",$phone)->first();
            if(!is_null($record)){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record->out_time_at) ){ //没有超过时限
                    try {
                        $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，申请退货业务，退货单：'.$return_order_id.'，您的授权码为'.$record->check_code);
                    } catch (Exception $e) {
                        Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                        $response = Lang::get("error.user_sms_check_code_send_error_1003");
                        break;
                    }
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                        'result' => array(
                            'out_time' => Common::datetime2Num($record->out_time_at) - time(),
                            // 'check_code' => $record->check_code // todo 调试使用
                        ));
                    break;
                }else{ //超过限时
                    $record->delete();
                }
            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();
            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，申请退货业务，退货单：'.$return_order_id.'，您的授权码为'.$check_code);
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_1003");
                break;
            }
            
            $record = new UserCheckCodeUpgrade;
            $record->business_type="return_washorder";
            $record->business_id=Input::get("return_order_id");
            $record->phone=$phone;
            $record->area="";
            $record->check_code=$check_code;
            $record->out_time_at=Common::num2DateTime(time() + $time_out_default);
            $record->send_id=$sms_send_record_id;           
            $record->save();
            
            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'out_time' => $time_out_default,
                )
            );
            
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
}